package edu.yctc.weblog.controller.impl;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import edu.yctc.weblog.constant.ConstantHolder;
import edu.yctc.weblog.constant.RequestAttributes;
import edu.yctc.weblog.constant.TemplatePath;
import edu.yctc.weblog.controller.BlogController;
import edu.yctc.weblog.entity.BlogDO;
import edu.yctc.weblog.service.BlogService;
import edu.yctc.weblog.service.CategoryService;
import edu.yctc.weblog.utils.UrlUtil;

@Controller
@RequestMapping(TemplatePath.S + TemplatePath.BLOGS)
public class BlogControllerImpl implements BlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private CategoryService categoryService;

    @Override
    @PostMapping(TemplatePath.BLOGS_MD + TemplatePath.S + TemplatePath.BLOGS_UPLOAD_FILE)
    public void uploadFileByEditormd(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(name = "editormd-image-file", required = true) MultipartFile file)
        throws IOException, URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        // 创建文件
        File destFile = new File(ConstantHolder.FILE_UPLOAD_DIC + newFileName);
        String fileUrl = UrlUtil.getHost(new URI(request.getRequestURL() + "")) + "/upload/" + newFileName;
        File fileDirectory = new File(ConstantHolder.FILE_UPLOAD_DIC);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            response.getWriter().write("{\"success\": 1, \"message\":\"success\",\"url\":\"" + fileUrl + "\"}");
        } catch (UnsupportedEncodingException e) {
            response.getWriter().write("{\"success\":0}");
        } catch (IOException e) {
            response.getWriter().write("{\"success\":0}");
        }

    }

    @Override
    @GetMapping(TemplatePath.BLOGS_EDIT)
    public String showBlogEdit(HttpServletRequest request) {
        request.setAttribute(RequestAttributes.PATH, RequestAttributes.VALUE_EDIT);
        request.setAttribute(RequestAttributes.CATEGORIES, categoryService.getAllCategories().getModule());
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.BLOGS_EDIT;
    }

    @Override
    @GetMapping(TemplatePath.BLOGS_PAGE)
    public String showBlogList(HttpServletRequest request) {
        request.setAttribute(RequestAttributes.PATH, RequestAttributes.VALUE_BLOGS);
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.BLOGS_PAGE;
    }

    @Override
    @GetMapping(TemplatePath.BLOGS_EDIT + TemplatePath.S + "{blogId}")
    public String edit(HttpServletRequest request, @PathVariable("blogId") Long blogId) {
        request.setAttribute(RequestAttributes.PATH, RequestAttributes.VALUE_EDIT);
        BlogDO blogDO = blogService.getBlogDOById(blogId).getModule();
        if (blogDO == null) {
            return TemplatePath.ERROR_400;
        }
        request.setAttribute(RequestAttributes.BLOG, blogDO);
        request.setAttribute(RequestAttributes.CATEGORIES, categoryService.getAllCategories().getModule());
        return TemplatePath.ADMIN + TemplatePath.S + TemplatePath.BLOGS_EDIT;
    }

}
